package cn.com.wxd.service.frendlink;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.GlobalConstant;
import cn.com.wxd.common.data.KVMap;
import cn.com.wxd.common.framedata.FrameDataUtil;

/**
 * 单例模式的FendLink类，该类自动加载和刷新友情连接和缓存友情连接
 * @author WangXuDong
 *
 */
public class FrendLink {
	private static final Logger log = LoggerFactory.getLogger(FrendLink.class);
	private static Document document = null;
	private static FrendLink frendLink;
	private static List<FrendLinkEntity> frendLinks;
	private FrendLink(){}
	public static FrendLink instance(){
		if(frendLink==null){
			frendLink = new FrendLink();
			frendLink.init();
			return frendLink;
		}
		if(document==null||frendLinks==null||frendLinks.size()<=0){
			frendLink.init();
		}
		return frendLink;
	}
	@SuppressWarnings("rawtypes")
	/**
	 * 初始化友情链接
	 * 一般在修改xml文件后执行次方法
	 */
	public void init(){
		try {
			SAXReader reader = new SAXReader(); 
			reader.setEncoding("UTF-8");
			String defaultXml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><frendlink><list></list></frendlink>";
			Element rootelement = DocumentHelper.parseText(defaultXml).getRootElement();
			//从数据库中获取数据
			String data = FrameDataUtil.getDataByName(GlobalConstant.FRENDLINKDATANAME);
			if(data==null||data.trim().equals("")){
				savaData(rootelement);
				data = defaultXml;
			}
			document = reader.read(new ByteArrayInputStream(data.getBytes("UTF-8")));
		} catch (DocumentException e) {
            log.error("读取友情链接文件错误！",e);
		} catch (Exception e) {
            log.error(e.getMessage(),e);
		}
		frendLinks = new ArrayList<FrendLinkEntity>();         

		//创建根节点  
		Element root = document.getRootElement();
		//获取list节点
		Element elelist = root.element("list");
		List nodes = elelist.elements("item"); 
		for (Iterator it = nodes.iterator(); it.hasNext();) {
			Element elm = (Element) it.next();
			FrendLinkEntity fe = new FrendLinkEntity();
			Element ename = elm.element("name");
			Element elink = elm.element("link");
			Element eaddress = elm.element("address");
			Element edescription = elm.element("description");
			Element etimestamp = elm.element("timestamp");
			Element eisshow = elm.element("isshow");
			Element eimagepath = elm.element("imagepath");
			if(ename!=null&&ename.getText()!=null){
				fe.setName(ename.getText());
			}else{
				fe.setName("");
			}
			if(elink!=null&&elink.getText()!=null){
				fe.setLink(elink.getText());
			}else{
				fe.setLink("");
			}
			if(eaddress!=null&&eaddress.getText()!=null){
				fe.setAddress(eaddress.getText());
			}else{
				fe.setAddress("");
			}
			if(edescription!=null&&edescription.getText()!=null){
				fe.setDescription(edescription.getText());
			}else{
				fe.setDescription("");
			}
			if(etimestamp!=null&&etimestamp.getText()!=null){
				fe.setTimeStamp(etimestamp.getText());
			}else{
				fe.setTimeStamp("");
			}
			if(eisshow!=null&&eisshow.getText()!=null){
				fe.setIsShow(eisshow.getText());
			}else{
				fe.setIsShow("false");
			}
			if(eimagepath!=null&&eimagepath.getText()!=null){
				fe.setImagePath(eimagepath.getText());
			}else{
				fe.setImagePath("");
			}
			frendLinks.add(fe);
		} 
	}
	/**
	 * 获取友情链接列表
	 * @return
	 */
	public List<FrendLinkEntity> getFrendLinks(){
		if(frendLinks==null||frendLinks.size()<=0){
			init();
		}
		return frendLinks;
	}
	/**
	 * 添加友情链接
	 * @param fle
	 * @throws IOException 
	 */
	public void addFrendLink(FrendLinkEntity fle){
		//创建根节点  
		if(fle==null){
			return;
		}
		if(fle.getName()==null){
			fle.setName("");
		}
		if(fle.getLink()==null){
			fle.setLink("");
		}
		if(fle.getDescription()==null){
			fle.setDescription("");
		}
		if(fle.getAddress()==null){
			fle.setAddress("");
		}
		if(fle.getTimeStamp()==null||fle.getTimeStamp().equals("")){
			fle.setTimeStamp(DateUtil.getTimestamp());
		}
		if(fle.getIsShow()==null||fle.getIsShow().equals("")){
			fle.setIsShow("false");
		}
		if(fle.getImagePath()==null||fle.getImagePath().equals("")){
			fle.setImagePath("");
		}
		Element root = document.getRootElement();
		//获取list节点
		Element elelist = root.element("list");
		Element elm = elelist.addElement("item");
		Element elmname = elm.addElement("name");
		//elmname.setText(fle.getName());
		elmname.addCDATA(fle.getName());
		Element ellink = elm.addElement("link");
		//ellink.setText(fle.getLink());
		ellink.addCDATA(fle.getLink());
		Element elmaddress = elm.addElement("address");
		elmaddress.setText(fle.getAddress());
		Element elmdiscript = elm.addElement("description"); 
		//elmdiscript.setText(fle.getDiscript());
		elmdiscript.addCDATA(fle.getDescription());
		Element elmtimestamp = elm.addElement("timestamp"); 
		elmtimestamp.setText(fle.getTimeStamp());
		Element elmisshow = elm.addElement("isshow"); 
		elmisshow.setText(fle.getIsShow());
		Element elmimagepath = elm.addElement("imagepath"); 
		//elmimagepath.setText(fle.getImagePath());
		elmimagepath.addCDATA(fle.getImagePath());
		savaData(root);
		init();
	}
	/**
	 * 删除一条友情链接,
	 * @param timeStamp 时间戳
	 */
	public void deleteFrendLink(String timeStamp){
		if(timeStamp==null){
			return;
		}
		//创建根节点  
		Element root = document.getRootElement();
		//获取list节点
		Element elelist = root.element("list");
		List<Element> nodes = elelist.elements("item"); 
		for (Iterator<Element> it = nodes.iterator(); it.hasNext();) {
			Element elm = it.next();
			Element etimestamp = elm.element("timestamp");
			if(etimestamp!=null&&etimestamp.getText().equalsIgnoreCase(timeStamp)){
				elelist.remove(elm);
			}
		}
		savaData(root);
		init();
	}
	/**
	 * 删除一条友情链接,
	 * @param name友情链接name
	 */
	public void deleteFrendLinkByName(String name){
		if(name==null){
			return;
		}
		//创建根节点  
		Element root = document.getRootElement();
		//获取list节点
		Element elelist = root.element("list");
		List<Element> nodes = elelist.elements("item"); 
		for (Iterator<Element> it = nodes.iterator(); it.hasNext();) {
			Element elm = it.next();
			Element ename = elm.element("name");
			if(ename!=null&&ename.getText().equalsIgnoreCase(name)){
				elelist.remove(elm);
			}
		}
		savaData(root);
		init();
	}
	/**
	 * 修改友情链接
	 * @param timeStamp 时间戳
	 * @param param key是节点 value是值
	 */
	public void editFrendLink(String timeStamp,KVMap<String, String> param){
		if(timeStamp==null){
			return;
		}
		//创建根节点  
		Element root = document.getRootElement();
		//获取list节点
		Element elelist = root.element("list");
		List<Element> nodes = elelist.elements("item"); 
		for (Iterator<Element> it = nodes.iterator(); it.hasNext();) {
			Element elm = it.next();
			Element etimestamp = elm.element("timestamp");
			if(etimestamp!=null&&etimestamp.getText().equalsIgnoreCase(timeStamp)){
				if(param!=null){
					List<Element> allnodes = elm.elements();
					for (Iterator<Element> allit = allnodes.iterator(); allit.hasNext();) {
						Element allele = allit.next();
						String nodeName = allele.getName();
						for (int j = 0; j < param.size(); j++) {
							if(param.getKeyIndex(j).equalsIgnoreCase(nodeName)){
								allele.setText(param.getValueIndex(j));
							}
						}
					}
				}
			}
		}
		savaData(root);
		init();
	}
	/**
	 * 保存数据
	 * @param _document
	 */
	private static void savaData(Element _document){
		String data = _document.asXML();
		try {
			FrameDataUtil.saveFrameData(GlobalConstant.FRENDLINKDATANAME, data);
		} catch (Exception e) {
            log.error("",e);
		}
	}
}
